上篇 提到 react 表單內的事件,來實際應用,做一個表單
在 表單 中寫 method 分別為
submitHandler: 按提交後的 method
handleChange: 每次 onChange 後 setState
clearInputs: 清空表單
import React from "react";
import { Button } from "react-bootstrap";
import Form from "react-bootstrap/Form";
// clear 時的 初始 state
const initialState = {
emailVal:'',
cellphoneVal:'',
favor:'choco'
}
class FormBtr extends React.Component {
constructor(props) {
super(props);
// 初始化 state
this.state = {
emailVal: "",
cellphoneVal: "",
favor:"mango"
};
// 將 method 綁到 class instance 上
this.submitHandler = this.submitHandler.bind(this);
this.handleChange = this.handleChange.bind(this);
this.clearInputs = this.clearInputs.bind(this);
}
// 寫在 form 上的 method
handleChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
submitHandler(e) {
e.preventDefault();
console.log("submit");
if (!this.state.emailVal || !this.state.cellphoneVal) {
alert("invalid value");
return false
}
alert(`
email:${this.state.emailVal}
cellphone:${this.state.cellphoneVal}
favor:${this.state.favor}
`);
this.clearInputs();
}
clearInputs(){
this.setState(initialState);
}
render() {
const { emailVal, cellphoneVal , favor } = this.state; // 從 state destructure
return (
<>
<h1>form from bootstrap</h1>
<Form onSubmit={this.submitHandler}>
<Form.Group controlId="formEmail">
<Form.Label>Email address</Form.Label>
<Form.Control
name="emailVal"
type="email"
placeholder="enter email"
value={emailVal}
onChange={this.handleChange}
/>
</Form.Group>
<Form.Group controlId="formCellphone">
<Form.Label>Cell phone</Form.Label>
<Form.Control
name="cellphoneVal"
type="number"
value={cellphoneVal}
placeholder="enter cellphone number"
onChange={this.handleChange}
/>
</Form.Group>
<Form.Group>
<Form.Label>
favorite favor
</Form.Label>
<Form.Control
as="select"
value={favor}
name="favor"
onChange={this.handleChange}
>
<option value="choco">Chocolate</option>
<option value="mango">Mango</option>
<option value='vanilla'>Vanilla</option>
</Form.Control>
</Form.Group>
<Button variant="primary" type="submit">
submit
</Button>
</Form>
</>
);
}
}
export default FormBtr;
點擊會顯示 整個表單輸入的 state
react bootstrap 表單的文件
https://react-bootstrap.github.io/components/forms/